package org.bite.verify;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.ICaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.bite.verify.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    @Autowired
    private CaptchaProperties captchaProperties;

    private static long VALID_TIME = 60 * 1000;
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        //第三方验证码
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
//        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight(), 4, 4);
        captcha.write(response.getOutputStream());

        //消除缓存
        response.setHeader("Pragma","No-cache");
        //设置返回格式
        response.setContentType("image/jpeg");

        //获取验证码
        System.out.println(captcha.getCode());

        //bug测试
        System.out.println("Code的key :"+captchaProperties.getSession().getCode());
        System.out.println("Data的key :"+captchaProperties.getSession().getDate());

        //存储session
        session.setAttribute(captchaProperties.getSession().getCode(),captcha.getCode());
        session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());

        //Servlet的OutputStream记得自行关闭哦！
        response.getOutputStream().close();
    }
    @RequestMapping("/check")
    public Boolean check(String captchaCode , HttpSession session){
        //参数校验

        //判断用户输入的验证码是否一致

        //是否有效期内
        if(!StringUtils.hasLength(captchaCode)){
            return false;
        }
//        String sessionCode = (String) session.getAttribute("CAPTCHA_SESSION_CODE");
        String sessionCode = (String) session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate = (Long)session.getAttribute(captchaProperties.getSession().getDate());

        //bug测试
        System.out.println("验证的值Code: "+sessionCode);
        System.out.println("验证的值Date: "+sessionDate);

        if(captchaCode.equalsIgnoreCase(sessionCode) && (System.currentTimeMillis() - sessionDate) < VALID_TIME){
            return true;
        }
        return false;
    }
}
